﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;

using Kingdee.BOS;
using Kingdee.BOS.Util;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.ServiceHelper.Excel;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.DataEntity;

namespace ReceiveProject
{
    [Description("收款单按钮事件")]
    public class ImportEntryEdit : AbstractBillPlugIn
    {
        /// <summary>
        /// 菜单点击事件
        /// </summary>
        /// <param name="e"></param>
        /// 
         public override void EntryBarItemClick(BarItemClickEventArgs e)
         {
             

             if (e.BarItemKey == "tb_JDQB_ImportEntry")
             {
                 // 显示文件上传界面，上传Excel文件
                 DynamicFormShowParameter showParam = new DynamicFormShowParameter();
                 //测试帐套 ke6c54dea96c24da1bef4fbd155c7ee04
                 //客户测试 ke6c54dea96c24da1bef4fbd155c7ee04
                 showParam.FormId = "ke6c54dea96c24da1bef4fbd155c7ee04";
                 this.View.ShowForm(showParam,
                 new Action<FormResult>((formResult) =>
                 {
                    if (formResult != null && formResult.ReturnData != null)
                    {
                        string fullFileName = formResult.ReturnData.ToString();
                        this.DoImportEntry(fullFileName);
                    }
                 }));
             }
         }

         /// <summary>
         /// 开始导入单据体
         /// </summary>
         /// <param name="fullFileName">Excel文件</param>
         /// <remarks>
         /// 特别说明：此函数仅演示如何把Excel转换为DataSet，
         /// 并读取DataSet内容，填写到单据体，
         /// 未进行任何的安全处理，实际生产环境，需要对数据的合法性进行严格的判断
         /// </remarks>
         /// 
         private void DoImportEntry(string fullFileName)
         {

             int i;
             using (ExcelOperation helper = new ExcelOperation(this.View))
             // 利用ExcelOperation对象，把xml文件，转为DataSet对象
             // 参数说明：
             // filePath : 完整的文件名，包含了物理目录
             // dataStartIndex : 数据开始行索引，从0开始。通常第一行为标题，第二行开始为数据行
             // colNameIndex : 列名所在行索引，从0开始。如此参数为0，表明第一行为列名行
             {
                 DataSet ds = helper.ReadFromFile(fullFileName, 1, 0);

                 DataTable dt = ds.Tables[0];


                 for (i = this.Model.GetEntryRowCount("F_PAEZ_Entity"); i >= 0; i--)
                 {

                     this.Model.DeleteEntryRow("F_PAEZ_Entity", i);

                 }
                 int rowIndex = this.Model.GetEntryRowCount("F_PAEZ_Entity");
                 foreach (DataRow dataRow in dt.Rows)
                 {
                     this.Model.CreateNewEntryRow("F_PAEZ_Entity");
                     this.Model.SetEntryCurrentRowIndex("F_PAEZ_Entity", rowIndex);
                     this.Model.SetValue("F_YR_BILLNO", dataRow["订单编号"], rowIndex);

                     double FDODate = double.Parse(dataRow["费用发生时间"].ToString());
                     DateTime FDate = DateTime.FromOADate(FDODate);
                     this.Model.SetValue("F_YR_DATETIME", FDate, rowIndex);

                     this.Model.SetValue("F_YR_AMOUNT", dataRow["金额"], rowIndex);
                     this.Model.SetValue("F_YR_FYX", dataRow["费用项"], rowIndex);
                     this.Model.SetValue("F_YR_JSFS", dataRow["结算方式"], rowIndex);

                     rowIndex++;
                 }
             }

         }
        /// <summary>
        /// 生成收款单
        /// </summary>
        /// <param name="e"></param>
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            string strsql, FCount, FChecker, FID;

            if (e.BarItemKey.EqualsIgnoreCase("tb_JD_SETRECEIVE"))
            {
                string FBillNo = this.Model.GetValue("FBillNo").ToString();

                strsql = "/*dialect*/ select count(*) from SK_JDQB_BILL where FBillNo ='" + FBillNo + "'";
                FCount = DBUtils.ExecuteScalar<string>(this.Context, strsql, string.Empty, null);

                if (FCount =="0")
                {
                    throw new KDBusinessException("", "单据还未保存，功能不可用");
                }
                else
                {
                    strsql = "/*dialect*/ select isnull(F_PAEZ_Checker,0) from SK_JDQB_BILL where FBillNo ='" + FBillNo + "'";
                    FChecker = DBUtils.ExecuteScalar<string>(this.Context, strsql, string.Empty, null);

                    if (FChecker == "0")
                    {
                        throw new KDBusinessException("", "单据还未审核，功能不可用");
                    }
                    else
                    {
                        strsql = "/*dialect*/ select FID from SK_JDQB_BILL where FBillNo ='" + FBillNo + "'";
                        FID = DBUtils.ExecuteScalar<string>(this.Context, strsql, string.Empty, null);

                        FInspectReceive(FID);

                        strsql = "/*dialect*/ select count(*) from SK_JDQB_BILLEntrys where F_SK_REBILLNO='' AND F_SK_NOTE='' and FID = " + FID + "";
                        FCount = DBUtils.ExecuteScalar<string>(this.Context, strsql, string.Empty, null);

                        if(FCount =="0")
                        {
                            this.View.ShowMessage("没有可生成的收款单，请检查", MessageBoxType.Notice);
                        }
                        else
                        {

                            FSETReceive(FID);
                            this.View.ShowMessage("收款单生成完毕，请检查", MessageBoxType.Notice);

                        }
                        
                    }
                }

            }
        }



        /// <summary>
        /// 检测来源订单号是否已生成收款单
        /// </summary>
        /// <param name="FID"></param>
        /// <returns></returns>
        public void FInspectReceive(string FID)
        {
            string strsql, FCount, F_SK_BILLNO, FENTRYID, FREBILLNO, F_SK_REBILLNO;
          
            int i;
            DataSet DSSK;
            DataTable DTSK;

            strsql = "/*dialect*/ select distinct F_SK_BILLNO,FENTRYID,F_SK_REBILLNO from SK_JDQB_BILLENTRYS where FID =" + FID + "";

            DSSK = DBUtils.ExecuteDataSet(this.Context, strsql);
            DTSK = DSSK.Tables[0];
            if (DTSK.Rows.Count > 0)
            {
                for (i = 0; i < DTSK.Rows.Count; i++)
                {
                    F_SK_BILLNO = DTSK.Rows[i]["F_SK_BILLNO"].ToString();
                    FENTRYID = DTSK.Rows[i]["FENTRYID"].ToString();
                    F_SK_REBILLNO = DTSK.Rows[i]["FENTRYID"].ToString();

                    strsql = "/*dialect*/ select count(*) from T_AR_RECEIVEBILL where FREMARK='" + F_SK_BILLNO + "'";
                    FCount = DBUtils.ExecuteScalar<string>(this.Context, strsql, string.Empty, null);

                    if (FCount != "0")
                    {
                        strsql = "/*dialect*/ select FBILLNO from T_AR_RECEIVEBILL where FREMARK='" + F_SK_BILLNO + "'";
                        FREBILLNO = DBUtils.ExecuteScalar<string>(this.Context, strsql, string.Empty, null);

                        strsql = "/*dialect*/ update SK_JDQB_BILLENTRYS set F_SK_NOTE ='',F_SK_REBILLNO='" + FREBILLNO + "' where FID =" + FID + " and FENTRYID = " + FENTRYID + "";
                        DBUtils.Execute(this.Context, strsql);

                    }
                    else
                    {
                        strsql = "/*dialect*/ update SK_JDQB_BILLENTRYS set F_SK_NOTE ='',F_SK_REBILLNO='' where FID =" + FID + " and FENTRYID = " + FENTRYID + "";
                        DBUtils.Execute(this.Context, strsql);
                    }


                    strsql = "/*dialect*/ select count(*) from T_ECC_NETORDER where FSOURCEORDERNUM ='" + F_SK_BILLNO + "'";
                    FCount = DBUtils.ExecuteScalar<string>(this.Context, strsql, string.Empty, null);

                    if (FCount == "0")
                    {
                        strsql = "/*dialect*/ update SK_JDQB_BILLENTRYS set F_SK_NOTE ='未找到B2C订单' where FID =" + FID + " and FENTRYID = " + FENTRYID + "";
                        DBUtils.Execute(this.Context, strsql);
                    }
                    else
                    {
                        strsql = "/*dialect*/ update SK_JDQB_BILLENTRYS set F_SK_NOTE ='',F_SK_REBILLNO='' where FID =" + FID + " and FENTRYID = " + FENTRYID + "";
                        DBUtils.Execute(this.Context, strsql);
                    }


                }
            }

            this.View.UpdateView("F_PAEZ_Entity1");
        }

        public void FSETReceive(string FID)
        {
            int i;
            string strsql, F_SK_BILLNO, FDate, F_SK_AMOUNT, F_SK_FYX, F_SK_REBILLNO, F_SK_JSFS;


            DataSet DSBCC;
            DataTable DTBCC;
            DataSet DSBCCE;
            DataTable DTBCCE;


            DataSet DSA;
            DataTable DTA;


            strsql = "/*dialect*/ select F_SK_BILLNO,convert(VARCHAR(10),F_SK_DATE,126) AS F_SK_DATE,F_SK_AMOUNT,F_SK_FYX,F_SK_JSFS from SK_JDQB_BILLEntrys where F_SK_REBILLNO='' AND F_SK_NOTE='' and FID =" + FID + "";
            DSA = DBUtils.ExecuteDataSet(this.Context, strsql);
            DTA = DSA.Tables[0];

             if (DTA.Rows.Count > 0)
             {
                 for (i = 0; i < DTA.Rows.Count; i++)
                 {
                     F_SK_BILLNO = DTA.Rows[i]["F_SK_BILLNO"].ToString();
                     FDate = DTA.Rows[i]["F_SK_DATE"].ToString();
                     F_SK_AMOUNT = DTA.Rows[i]["F_SK_AMOUNT"].ToString();
                     F_SK_FYX = DTA.Rows[i]["F_SK_FYX"].ToString();
                     F_SK_JSFS = DTA.Rows[i]["F_SK_JSFS"].ToString(); ;

                     strsql = "/*dialect*/ select '" + F_SK_BILLNO + "' as  FREMARK, " + F_SK_AMOUNT + " as FRECEIVEAMOUNTFOR_H, '" + FDate + "' as FDate, t2.FNUMBER as FSALEORGID,t3.FNUMBER as FSETTLEORGID,t4.FNUMBER as FPAYORGID,t5.FNUMBER as FPAYUNIT   from  T_ECC_SHOP t1 " +
                            "left join T_ORG_Organizations t2 on t1.FSALEORGID =t2.FORGID " +
                            "left join T_ORG_Organizations t3 on t1.FSETTLEMENTORGID =t3.FORGID " +
                            "left join T_ORG_Organizations t4 on t1.FBILLORGID =t4.FORGID " +
                            "left join T_BD_CUSTOMER t5 on t1.FCUSTOMERID =t5.FCUSTID " +
                            "where  FID =(select FNETORDERSOURCE from T_ECC_NETORDER where FSOURCEORDERNUM='" + F_SK_BILLNO + "')";

                     DSBCC = DBUtils.ExecuteDataSet(this.Context, strsql);
                     DTBCC = DSBCC.Tables[0];

                     strsql = " /*dialect*/ select '" + F_SK_FYX + "' as F_SK_FYX," + F_SK_AMOUNT + " as FRECTOTALAMOUNTFOR ,'" + F_SK_JSFS + "' as F_SK_JSFS";
                     DSBCCE = DBUtils.ExecuteDataSet(this.Context, strsql);
                     DTBCCE = DSBCCE.Tables[0];

                     DataSet ds = new DataSet();
                     DataTable dt1 = new DataTable();
                     DataTable dt2 = new DataTable();

                     dt1 = DTBCC.Copy();
                     dt2 = DTBCCE.Copy();

                     dt1.TableName = "ReceiveBill";
                     dt2.TableName = "ReceiveBillEntry";

                     ds.Tables.Add(dt1);
                     ds.Tables.Add(dt2);

                     IMPORTRECIVE im = new IMPORTRECIVE();
                     F_SK_REBILLNO = im.SAL_ReceiveBill(ds).ToString();

                     setBiLLno(F_SK_BILLNO, FID, F_SK_REBILLNO);


                     DSBCC.Clear();
                     DSBCCE.Clear();
                 }
             }
        }

        public void setBiLLno(string F_SK_BILLNO, string FID, string F_SK_REBILLNO)
        {
            string strsql;
            if (F_SK_REBILLNO != "")
            {
                strsql = "/*dialect*/ update SK_JDQB_BILLENTRYS set F_SK_REBILLNO = '" + F_SK_REBILLNO + "' where FID =" + FID + " and F_SK_BILLNO ='" + F_SK_BILLNO + "'";
                DBUtils.Execute(this.Context, strsql);
            }
        }

    }
}
